package com.dwm716.shorturl.service.impl;

import com.dwm716.shorturl.domain.User;
import com.dwm716.shorturl.mapper.UserMapper;
import com.dwm716.shorturl.pagehelper.PageResult;
import com.dwm716.shorturl.service.UserService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Objects;

/**
 * @author biliyu
 * @date 2023/6/7 08:58
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;


    @Override
    public void insert(User user) {
        userMapper.insert(user);
    }

    @Override
    public void update(User user) {
        userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public PageResult<User> list(List<String> statusList, Integer pageNo, Integer pageSize) {
        com.github.pagehelper.Page<Object> page = PageHelper.startPage(pageNo, pageSize);
        Example example = new Example(User.class);
        example.createCriteria().andIn("status", statusList);
        List<User> users = userMapper.selectByExample(example);
        return PageResult.create(users, page.getTotal(), page.getPageSize());
    }

    @Override
    public User login(User user) {
        String name = user.getName();
        String password = user.getPassword();
        Example example = new Example(User.class);
        example.createCriteria().andEqualTo("name", name);
        List<User> users = userMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(users)) {
            throw new RuntimeException("名称或者密码错误");
        }
        User user1 = users.get(users.size() - 1);
        if (!Objects.equals(user1.getPassword(), password)) {
            throw new RuntimeException("名称或者密码错误");
        }
        return user1;

    }

    @Override
    public User getById(Integer userId) {
        return userMapper.selectByPrimaryKey(userId);
    }

    @Override
    public List<User> getByName(String name) {
        Example example = new Example(User.class);
        example.createCriteria().andEqualTo("name", name);
        return userMapper.selectByExample(example);
    }

}
